<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace Svick\OS;


class OS
{
    /**
     * 获取系统IP地址
     *
     * @return string
     */
    public static function ip(): string
    {
        $preg = "/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/";

        //获取操作系统为windows的本机IP真实地址
        $ip = '127.0.0.1';
        exec('ipconfig', $out, $stats);
        if (!empty($out)) {
            foreach ($out as $row) {
                if (strstr($row, "IP") && strstr($row, ":") && !strstr($row, "IPv6")) {
                    $temp = explode(":", $row);
                    if (preg_match($preg, trim($temp[1]))) {
                        $ip = trim($temp[1]);
                    }
                } elseif (strstr($row, 'Default Gateway') && strlen(substr($row, strpos($row, ':'))) > 7) {
                    return $ip;
                }
            }
        }

        //获取操作系统为linux类型的本机IP真实地址
        exec('ifconfig', $out, $stats);
        if (!empty($out)) {
            if (isset($out[1]) && strstr($out[1], 'addr:')) {
                $tmpArray = explode(":", $out[1]);
                $temp = explode(" ", $tmpArray[1]);
                if (preg_match($preg, trim($temp[0]))) {
                    return trim($temp[0]);
                }
            }
        }

        return $ip;
    }
}
